import React, { useState } from 'react'
import { Card, Typography, Form, Input, Button, Divider, Drawer, Modal, Slider } from 'antd'
import {
  ReloadOutlined
} from '@ant-design/icons'
import styles from '@/styles/sign.module.scss'
import { storage, successMsg, errorMsg } from '@/utils/utils'
import { telephone } from '@/utils/regexp.js'
import md5 from 'js-md5'
import Protocol from '../protocol/index.js'
import { useRouter } from 'next/router'
import loginModel from 'pages/model/login/index.js'
import Image from 'next/image'
import LeYi from '@/public/images/LeYi.svg'
 
const { Title } = Typography
function Sign () {
  const [sign, setSign] = useState(true)
  const [visible, setVisible] = useState(false)
  // modal
  const router = useRouter()
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [sliderValue, setSliderValue] = useState(0)
  const [randomValue, setRandomValue] = useState(0)
  const [loginForm] = Form.useForm()
  const [registerForm] = Form.useForm()
  const changeSign = () => {
    setSign(!sign)
  }
  const onClose = () => {
    setVisible(false)
  }
  // 登录
  const toLogin = () => {
    loginForm.validateFields().then(values => {
      loginModel.toLogin({
        data: {
          account: values.username,
          password: md5(values.password)
        }
      }).then(data => {
        if (data.success) {
          successMsg(data.message)
          storage.set('next_blog_userInfo', JSON.stringify(data.datas))
          storage.set('next_blog_tokens', data.tokens)
          storage.set('isLogin', 1)
          router.push('/') 
        }
      })
    })
  }
  // 随机生成x-xx之间的数值
  const randomNum = (max, min) => Math.floor(Math.random() * (max - min)) + min
  // 注册
  const register = () => {
    registerForm.validateFields().then(values => {
      if (telephone.test(values.registerIphone)) {
        setIsModalVisible(true)
        // 随机生成1-100
        setRandomValue(randomNum(100, 1))
      } else {
        errorMsg('手机格式错误!')
      }
    })
  }
  const handleOk = () => {
    if (sliderValue === randomValue) {
      setIsModalVisible(false)
      registerForm.validateFields().then(values => {
        if (telephone.test(values.registerIphone)) {
          loginModel.userRegister({
            data: {
              iphone: values.registerIphone,
              password: md5(values.registerPassword)
            }
          }).then(data => {
            if (data.success) {
              successMsg('注册成功,快去登录吧~')
              setSign(true) 
            }
          })
        } else {
          errorMsg('手机格式错误!')
        }
      })
    } else {
      errorMsg('验证失败')
      setSliderValue(0)
      setRandomValue(randomNum(100, 1))
    }
  }
  // 滑动输入数值
  const sliderOnChange = (value) => {
    setSliderValue(value)
  }
  // 刷新
  const refreshIcon = () => {
    setSliderValue(0)
    setRandomValue(randomNum(100, 1))
  }
  return (
    <div className={styles.main}>
      <div className={styles.login}>
        <div className={styles.logo}>
          <Image src={LeYi} width={120}  height={120}></Image>
        </div>
        <div className={styles.login_main}>
          <div>
            <div style={{display: sign ? 'block' : 'none'}}>
              <Card bordered={false} style={{ width: 380, height: '100%'}}>
                <Title level={4} style={{color: '#1890ff'}}>登 录</Title>
                <Divider></Divider>
                <Form
                  autoComplete="off"
                  form={loginForm}
                >
                  <Form.Item
                    name="username"
                    rules={[{required: true, message: '请输入账号!'}]}
                  >
                    <Input size="large" placeholder="手机号或邮箱" bordered={false} style={{borderBottom: '1px solid #ebebeb'}} />
                  </Form.Item>

                  <Form.Item
                    name="password"
                    rules={[{required: true, message: '请输入密码!'}]}
                  >
                    <Input.Password size="large" placeholder="密码" bordered={false} style={{borderBottom: '1px solid #ebebeb'}} />
                  </Form.Item>
                </Form>
                <div className={styles.forgetPsd}><Button type="text">忘记密码？</Button></div>
                <Button type="primary" size="large" onClick={toLogin} style={{width: '100%', marginTop: 20}}>登 录</Button>
                <div className={styles.register}><Button type="text" onClick={changeSign}>没有账号？去注册</Button></div>
              </Card>
            </div>
            <div style={{display: sign ? 'none' : 'block'}}>
              <Card bordered={false} style={{ width: 380, height: '100%'}}>
                <Title level={4} style={{color: '#1890ff', textAlign: 'right'}}>注 册</Title>
                <Divider></Divider>
                <Form
                  autoComplete="off"
                  form={registerForm}
                >
                  <Form.Item
                    name="registerIphone"
                    rules={[{required: true, message: '请输入手机号!'}]}
                  >
                    <Input size="large" maxLength={11} placeholder="手机号" bordered={false} style={{borderBottom: '1px solid #ebebeb'}} />
                  </Form.Item>

                  <Form.Item
                    name="registerPassword"
                    rules={[{required: true, message: '请输入密码!'}]}
                  >
                    <Input.Password size="large" placeholder="密码" bordered={false} style={{borderBottom: '1px solid #ebebeb'}} />
                  </Form.Item>
                </Form>
                <div className={styles.forgetPsd}><Button type="text">注册即代表同意<span onClick={() => setVisible(true)} style={{color: '#1890ff'}}>《乐一博客协议》</span></Button></div>
                <Button type="primary" size="large" onClick={register} style={{width: '100%', marginTop: 20}}>注 册</Button>
                <div className={styles.register}><Button type="text" onClick={changeSign}>已有账号？去登录</Button></div>
              </Card>
            </div>
          </div>
        </div>
      </div>
      <Drawer
        title="乐一博客协议（草案）"
        placement="right"
        closable={false}
        onClose={onClose}
        visible={visible}
        width={500}
      >
        <Protocol></Protocol>
      </Drawer>
      <Modal title="人机校验" keyboard={false} okText="确定" cancelText="取消"  centered={true} maskClosable={false} destroyOnClose={true} visible={isModalVisible} onOk={handleOk} onCancel={() => setIsModalVisible(false)}>
        <Title level={1} style={{textAlign: 'center', height: 70}}>{randomValue}<ReloadOutlined style={{fontSize: 20, marginLeft: 15, color: '#1890ff', cursor: 'pointer'}} onClick={refreshIcon} /></Title>
        <Slider value={sliderValue} onChange={sliderOnChange} tooltipVisible />
        <h4>滑动数值一致完成校验</h4>
      </Modal>
    </div>
  )
}

export default Sign